//
//  ModifyPersonInfoViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-14.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "ModifyPersonInfoViewController.h"

@interface ModifyPersonInfoViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
/**
 *  输入框
 */
@property (strong, nonatomic) IBOutlet UITextField *attributeTextField;
/**
 *  要上传的数据存在此字典中
 */
@property (nonatomic, strong) NSMutableDictionary *uploadInfoDic;
/**
 *  存放类型的字典
 */
@property (nonatomic, strong) NSDictionary *typeDic;
/**
 *  书写真实姓名时的文案
 */
@property (nonatomic, strong) UITextView *realNameTextView;
@end

@implementation ModifyPersonInfoViewController

- (NSMutableDictionary *)uploadInfoDic{
    if (_uploadInfoDic == nil) {
        self.uploadInfoDic = [NSMutableDictionary dictionary];
    }
    return _uploadInfoDic;
}


- (NSDictionary *)typeDic{
    if (_typeDic == nil) {
        self.typeDic = [NSDictionary dictionary];
    }
    return _typeDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviBarAttribute];
    self.attributeTextField.delegate = self;
    self.navigationItem.title = self.tabTitle;
    self.view.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.attributeTextField.placeholder = self.placehoderString;
    /**
     *  不同的键盘样式
     */
  if ([self.tabTitle isEqualToString:@"个人邮箱"]){
        self.attributeTextField.keyboardType = UIKeyboardTypeEmailAddress;
    }else if([self.tabTitle isEqualToString:@"身份证"]){
        self.attributeTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    }else{
        self.attributeTextField.keyboardType = UIKeyboardTypeTwitter;
    }
    // 存放次字典是为了获取上传时字典的key;
    self.typeDic = @{@"昵称":@"username",@"真实姓名":@"realname",@"身份证":@"idcard",@"个人邮箱":@"email"};
    
    self.attributeTextField.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
    [self.view addSubview:self.realNameTextView];
    if ([self.tabTitle isEqualToString:@"真实姓名"]) {
        self.realNameTextView.hidden = NO;
    }else{
        self.realNameTextView.hidden = YES;
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.attributeTextField becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


// block 传值
- (void)getTextFieldInfo:(backPersonalDataAttributeInfo)string{
    self.personalDataInfo = string;
}

#pragma mark - 设置naviBar 并实现左右naviBar button方法 - 
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 23, 23);
    [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}


/**
 *  返回
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction{
    [self.uploadInfoDic setValue:self.attributeTextField.text forKey:[self.typeDic objectForKey:self.tabTitle]];
//    [self _parsePersonalDataSource:kBaseURL];
    if([self.tabTitle isEqualToString:@"真实姓名"]){
        if (self.attributeTextField.text.length > 5 || self.attributeTextField.text.length <= 1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"真实姓名在2位到4位之间,并且修改后不可再次修改" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }else{
//            self.personalDataInfo(self.attributeTextField.text);
//            [self.navigationController popViewControllerAnimated:YES];
            [self _parsePersonalDataSource:kBaseURL];
        }
    }else if ([self.tabTitle isEqualToString:@"身份证"]){
        if (self.attributeTextField.text.length == 15 || self.attributeTextField.text.length == 18) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改后将不可再次修改" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",@"取消", nil];
            [alert show];
//            self.personalDataInfo(self.attributeTextField.text);
//            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"身份证填写有误" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }else{
//        self.personalDataInfo(self.attributeTextField.text);
//        [self.navigationController popViewControllerAnimated:YES];
        [self _parsePersonalDataSource:kBaseURL];
    }
}


#pragma mark - 网路数据上传 -
- (void)_parsePersonalDataSource:(NSString *)urlString{
    [self showActionView];
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/changeuser/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [self.uploadInfoDic setValue:kPlatform forKey:@"platform"];
    [self.uploadInfoDic setValue:kVersion forKey:@"version"];
    
    [manager POST:postURL parameters:self.uploadInfoDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
//            [self showCustomHudSingleLine:@"输入错误"];
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            MyNSLog("======%@========", [responseObject objectForKey:@"msg"]);
            UserModel *userModel = [[UserManager shareInstance]getUserInfo];
            NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];

            self.personalDataInfo(self.attributeTextField.text);
            if([self.tabTitle isEqualToString:@"真实姓名"])
            {
                [userDefaults setValue:self.attributeTextField.text forKey:[NSString stringWithFormat:@"%@realname",userModel.uid]];
            }
            else if ([self.tabTitle isEqualToString:@"身份证"])
            {

//                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//                [formatter setDateFormat:@"yyyy"];
//                [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
//                NSString *afterDate=[formatter stringFromDate:[NSDate date]];
//                NSString *forgeDate=[self.attributeTextField.text substringWithRange:NSMakeRange(6,4)];
//                NSString *temDate=[NSString stringWithFormat:@"%d",[afterDate integerValue]-[forgeDate integerValue]];
//                [userDefaults setValue:temDate forKey:[NSString stringWithFormat:@"%@age",userModel.uid]];

            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        MyNSLog("sss");
        [self hiddenActionView];
    } failure:nil];
}


#pragma mark - alertView的代理方法 -
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self _parsePersonalDataSource:kBaseURL];
    }
}


- (UITextView *)realNameTextView{
    if (_realNameTextView == nil) {
        if (kScreenWidth == 414) {
            _realNameTextView = [[UITextView alloc] initWithFrame:CGRectMake(8, 60, kScreenWidth - 16, 54)];
        }else{
            _realNameTextView = [[UITextView alloc] initWithFrame:CGRectMake(8, 60, kScreenWidth - 16, 44)];
        }
        _realNameTextView.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13 + 1];
        _realNameTextView.backgroundColor = [UIColor clearColor];
        _realNameTextView.text = @"请保证您问诊、病例信息的统一，请填写真实姓名，确定后不可修改。";
        _realNameTextView.editable = NO;
        _realNameTextView.selectable = NO;
    }
    return _realNameTextView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
